
# Set up the packages, options, and working directory path
pacman::p_load(tidyverse, haven, fixest)
set.seed(42)
options(scipen=999)
if (Sys.info()[['user']] == "alal") {
  root = "/home/alal/Dropbox/1_Research/ElecAdminFunding/ElecAdminFundingReplication"
} else {
  root = "~/Dropbox/ElecAdminFunding/ElecAdminFundingReplication"
}

# Set up the dataset for selection
ctcl = haven::read_dta(file.path(root, "/modified_data/ctcl.dta")) %>%
  select(state, fips, policy_year, treat, vs_dem_pres, turnout_pres) %>%
  rename(vs = vs_dem_pres, tur = turnout_pres) %>%
  pivot_wider(names_from=policy_year, values_from=c("vs", "tur"), names_sep="")

# Run the lagged-dependent-variable regressions
ldv1 = feols(vs2020 ~ treat + vs2016 + vs2012 + vs2008 + vs2004 + vs2000 + vs1996 + vs1992, data=ctcl, se="hetero")
ldv2 = feols(vs2020 ~ treat + vs2016 + vs2012 + vs2008 + vs2004 + vs2000 + vs1996 + vs1992 | state, data=ctcl, se="hetero")
ldv3 = feols(tur2020 ~ treat + tur2016 + tur2012 + tur2008 + tur2004 + tur2000 + tur1996 + tur1992, data=ctcl, se="hetero")
ldv4 = feols(tur2020 ~ treat + tur2016 + tur2012 + tur2008 + tur2004 + tur2000 + tur1996 + tur1992 | state, data=ctcl, se="hetero")

# Put the output into a matrix
out = matrix(nrow=4, ncol=4)
out[1, ] = c(ldv1$coefficients['treat'], ldv2$coefficients['treat'], 
  ldv3$coefficients['treat'], ldv4$coefficients['treat'])
out[2, ] = c(ldv1$se['treat'], ldv2$se['treat'], 
  ldv3$se['treat'], ldv4$se['treat'])
out[3, ] = rep(table(ctcl$treat)[2], 4)
out[4, ] = c(ldv1$nobs, ldv2$nobs, ldv3$nobs, ldv4$nobs)

# Put the selection regression estimates in a tex table for the paper
cat(
"\\begin{table}[ht]",
"\\centering",
"\\caption{\\textbf{Election Administration Grants Did Not Substantially Advantage Democrats or Increase Turnout
in 2020, Within-State Estimates.}",
"\\label{tab:within_state}}",
"\\begin{tabular}{lcc|cc}",
"\\toprule \\toprule",
" & \\multicolumn{2}{c}{Dem Vote Share (\\%)} & \\multicolumn{2}{c}{Turnout (\\%)} \\\\",
" & (1) & (2) & (3) & (4) \\\\",
"\\midrule",
sprintf("Grant Recipient in 2020 & %1.2f & %1.2f & %1.2f & %1.2f \\\\",
  out[1,1], out[1,2], out[1,3], out[1,4]),
sprintf(" & (%1.2f) & (%1.2f) & (%1.2f) & (%1.2f) \\\\[2mm]",
  out[2,1], out[2,2], out[2,3], out[2,4]),
sprintf("Num Recipients & %4.0f & %4.0f & %4.0f & %4.0f \\\\",
  out[3,1], out[3,2], out[3,3], out[3,4]),
sprintf("Num Counties & %4.0f & %4.0f & %4.0f & %4.0f \\\\",
  out[4,1], out[4,2], out[4,3], out[4,4]),
"\\midrule",
"State FEs & No & Yes & No & Yes \\\\",
"\\bottomrule \\bottomrule",
"\\multicolumn{5}{p{0.7\\textwidth}}{\\footnotesize Robust standard reported in parentheses. ",
"Each column reports estimates from a lagged dependent variable regression with lags from the ",
"seven prior presidential elections (1992 to 2016) included as regressors.}",
"\\end{tabular}",
"\\end{table}",
file=paste0(root, "/output/within_state_table.tex"), sep="\n")


